<?php
/*
$handler = function($a){
	echo 'aim function a:'.$a.PHP_EOL;
};
$filter = function($handler){
	echo 'filter function '.PHP_EOL;
	return function($a)use($handler){
		$a++;
		return $handler($a);
	};
};
$stack = [];
$stack['filter'] = $filter;
function run($handler, $stack){
	foreach(array_reverse($stack) as $k=>$middleware){
		echo $k;
		$handler = $middleware($handler);
	}
	return $handler;
}
$r = run($handler, $stack);
$r(1);
*/

//应用层
$handler = function($name) {
    $name ++;
    echo "{$name} application<br/>";
};
//前置过滤中间件
$filter = function($handler) {
    return function($name) use ($handler) {
        $name ++;
        echo "{$name} filter<br/>";
        return $handler($name);
    };
};
//前置校验中间件
$auth = function($handler) {
    return function($name) use ($handler) {
        $name ++;;
        echo "{$name} auth <br/>";
        return $handler($name);
    };
};
//后置日志中间件
$log = function($handler) {
    return function($name) use ($handler) {
        $return = $handler($name);
        $name ++;
        echo "{$name} log<br/>";
        return $return;
    };
};
//执行中间件
function run($handler, $stack)
{
    foreach (array_reverse($stack) as $key => $middleware) {
        $handler = $middleware($handler);
    }
    return $handler;
}
// 中间件栈
$stack = [];
// 注册中间件
$stack['log'] = $log;
$stack['filter'] = $filter;
$stack['auth'] = $auth;

$run = run($handler, $stack);   //等同于$run = $log($filter($auth($handler)));
$run(1);
